package com.wlyuan.index.domain.source.valueobj;

import com.wlyuan.core.domain.valueobj.QuotationId;
import com.wlyuan.index.domain.source.Combine;
import com.wlyuan.tools.utils.CallUtils;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.BooleanUtils;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;

/**
 * @author yuanjie
 */
@Slf4j
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true, exclude = {"combine", "quotations"})
public class CombineRelation extends Combine.Relation {
    private final Combine combine;
    private final List<Quotation> quotations = new ArrayList<>();

    public CombineRelation(Combine combine, Combine.Relation relation) {
        super(relation);
        this.combine = combine;
    }

    public void addQuotations(List<Quotation> quotations) {
        this.quotations.addAll(quotations);
    }

    private Quotation quotation() {
        return quotations.stream()
                .max(Comparator.comparingInt(Quotation::getPriority))
                .orElse(null);
    }

    public QuotationStatus getQuotationStatus() {
        if (null == this.getStatus()) {
            return null;
        }

        // 合单已关闭或已过关账期
        if (CombineStatus.CLOSED == this.getStatus()
                || BooleanUtils.isTrue(combine.getEndBill())) {
            return QuotationStatus.CLOSED;
        }

        // 存在报价单，则显示报价单状态
        return CallUtils.call(Quotation::getStatus, this.quotation());
    }

    public QuotationId getQuotationId() {
        return CallUtils.call(Quotation::getQuotationId, this.quotation());
    }

    public QuotationNo getQuotationNo() {
        return CallUtils.call(Quotation::getQuotationNo, this.quotation());
    }

    public boolean isCanQuote() {
        // 运单状态为空不能报价
        if (null == this.getStatus()) {
            return false;
        }

        if (BooleanUtils.isTrue(this.getEndQuote())) {
            // 主动标记为不能报价
            return false;
        }

        // 合单不能报价
        if (!this.combine.isCanQuote()) {
            return false;
        }

        if (!this.getStatus().isCanQuote()) {
            return false;
        }

        // 报价单状态
        return Optional.ofNullable(this.getQuotationStatus())
                .map(QuotationStatus::isCanQuote)
                .orElse(true);
    }
}